﻿using System.Collections.Generic;
using IDAL;
using Model;
using NHibernate;

namespace SqlDALLibrary
{
    public class DepartmentDal : IDepartmentDAL
    {

        public void saveDepartment(Department department)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Save(department);
                tx.Commit();
            }
            session.Close();
        }

        public void updateDepartment(Department department)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Update(department);
                tx.Commit();
            }
            session.Close();
        }

        public void delDepartment(Department department)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Delete(department);
                tx.Commit();
            }
            session.Close();
        }

        public IList<Department> getDepartment()
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<Department> departmentList = session
                    .CreateQuery("from Department")
                    .List<Department>();
            session.Close();
            return departmentList;
        }

        public Department getDepartment(int id)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            Department department = session
                    .CreateQuery("from Department d where d.id=:id")
                    .SetInt32("id", id)
                    .UniqueResult<Department>();
            session.Close();
            return department;
        }

        public Department getDepartment(string name)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            Department department = session
                    .CreateQuery("from Department d where d.name=:name")
                    .SetString("name", name)
                    .UniqueResult<Department>();
            session.Close();
            return department;
        }
    }
}
